package com.citywithincity.db.sync;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.util.TextUtils;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import com.citywithincity.db.interfaces.IValueConvert;
import com.citywithincity.utils.ClassUtil;
import com.citywithincity.utils.StringUtils;
import com.damai.plugins.BaseJob;

public class DbSyncJob extends BaseJob {

	private static final Log logger = LogFactory.getLog("syncData");
	
	
	private static final Map<String, Boolean> taskMap = Collections.synchronizedMap(new HashMap<String, Boolean>());
	
	@Override
	protected void doJob(JobExecutionContext j) throws JobExecutionException  {
		//首先加载数据,从本地加载最大id
		JobDataMap context = j.getMergedJobDataMap();
		String srcTable = (String)context.get("srcTable");
		
		if(taskMap.containsKey(srcTable)){
			return;
		}
		
		taskMap.put(srcTable, true);
		try{

			String[] srcFields = (String[]) context.get("srcFields");
			String[] targetFields = (String[])context.get("targetFields");
			String[] converts = (String[])context.get("converts");
			
			int targetDb = (Integer)context.get("targetDb");
			int srcDb = (Integer)context.get("srcDb");
			
			String method = (String)context.get("method");
			
			
			
			
			
			
			String targetTable = (String)context.get("targetTable");
			String dataHandler = (String) context.get("dataHandler");
			String after = (String) context.get("after");
			
			
			
			IValueConvert[] convertArray = new IValueConvert[srcFields.length];
			int index = 0;
			for (String convertClass : converts) {
				if(!StringUtils.isEmpty(convertClass)){
					try {
						convertArray[index] = ClassUtil.newInstance(convertClass);
					} catch (Exception e) {
						throw new JobExecutionException(e);
					}
				}
				++ index;
			}
			
			SyncDataHandler handler = null;
			if(!StringUtils.isEmpty(dataHandler)){
				try {
					handler = ClassUtil.newInstance(dataHandler);
				} catch (Exception e) {
					throw new JobExecutionException(e);
				}
			}
			String uniqueKeys = (String) context.get("uniqueKeys");
			SyncInsertMethod insertMethod ;
			String insert = (String)context.get("insert");
			if(StringUtils.isEmpty(uniqueKeys)){
				insertMethod = new DirectInsert(targetTable);
			}else{
				if(insert!=null && insert.equals("insertOrUpdate")){
					if(StringUtils.isEmpty(uniqueKeys)){
						throw new RuntimeException("必须定义uniqueKeys");
					}
					if(uniqueKeys.contains(",")){
						throw new RuntimeException("暂不支持uniqueKeys包含,的情况");
					}
					insertMethod = new InsertOrUpdate(targetTable, uniqueKeys);
				}else{
					insertMethod = new InsertCheckUnique(targetTable,uniqueKeys);
				}
			}
			
			String conditionName = (String)context.get("condition");
			
			SyncCondition condition;
			try {
				condition = ClassUtil.newInstance( conditionName );
			} catch (Exception e) {
				throw new JobExecutionException(e);
			}
			SyncAfter syncAfter = null;
			if(!StringUtils.isEmpty(after)){
				try {
					syncAfter = ClassUtil.newInstance( after );
				} catch (Exception e) {
					throw new JobExecutionException(e);
				}
			}
			
			String extraFields = context.getString("extraFields");
			SyncFieldsContainer container = new SyncFieldsContainer(srcFields,
					targetFields, convertArray, targetDb, handler,syncAfter);
			ISyncData all;
			if(method.equals(DbSyncUtil.METHOD_ALL)){
				all = new SyncProgressAll(srcDb,
						srcTable,
						srcFields,
						container,
						insertMethod,
						condition,
						extraFields);
			}else{
				int pageSize = (Integer)context.get("pageSize");
				all = new SyncProgressPage(srcDb,
						srcTable,
						srcFields,
						container,
						insertMethod,
						condition,
						pageSize,
						extraFields);
			}
			logger.info(new StringBuilder().append("S开始同步数据[").append(context.get("name")).append("]").toString());
			all.syncData();
			String complete = (String)context.get("complete");
			if(!TextUtils.isEmpty(complete)){
				try {
					SyncComplete c = ClassUtil.newInstance( complete );
					c.onSyncComplete();
				} catch (Exception e) {
					throw new JobExecutionException(e);
				}
			}
			logger.info(new StringBuilder().append("E同步数据[").append(context.get("name")).append("]结束").toString());
			all.destroy();
		}finally{
			taskMap.remove(srcTable);
		}
		
	}
	
	

}
